import { Directive, Input, TemplateRef, ViewContainerRef, OnInit, NgZone, OnChanges, SimpleChanges, ViewRef, EmbeddedViewRef, ElementRef } from '@angular/core';
import { NzFormControlComponent } from 'ng-zorro-antd';

@Directive({
  selector: '[bzExplain]'
})
export class ExplainDirective implements OnInit, OnChanges {

  @Input() bzExplain: TemplateRef<null> | string;
  @Input() bzExplainContext: any;

  private hostEle: HTMLDivElement;
  private viewRef: EmbeddedViewRef<TemplateRef<null>>;
  private setupExplainTimeoutId: any;

  constructor(
    private elementRef: ElementRef,
    private viewContainerRef: ViewContainerRef,
    private ngZone: NgZone
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.bzExplain || changes.bzExplainContext) {
      if (!this.hostEle) {
        this.hostEle = this._initEle();
      }

      this.setupExplain();
    }
  }

  ngOnInit(): void {

  }

  private setupExplain() {
    clearTimeout(this.setupExplainTimeoutId);

    this.ngZone.runOutsideAngular(() => {
      this.setupExplainTimeoutId = setTimeout(() => {
        if (typeof this.bzExplain === 'string') {
          this.hostEle.innerHTML = this.bzExplain;
        } else {
          if (this.viewRef) {
            this.viewRef.rootNodes.forEach(rootNode => this.hostEle.removeChild(rootNode));
            this.viewRef.destroy();
          }
          this.viewRef = this.viewContainerRef.createEmbeddedView(<TemplateRef<null>>this.bzExplain, this.bzExplainContext);
          this.viewRef.rootNodes.forEach(rootNode => this.hostEle.appendChild(rootNode));
          this.viewRef.detectChanges();
        }
      }, 300);
    });
  }

  private _initEle() {
    const formControlEle = this.elementRef.nativeElement;

    const hostEle = document.createElement('div');
    hostEle.className = 'custom-explain';
    // hostEle.style.cssText = `
    //   height: 1em;
    //   text-align: right;
    // `;
    formControlEle.appendChild(hostEle);
    return hostEle;
  }
}
